package com.hulman.oms.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Sentence;
import com.hulman.oms.bean.Sign;
import com.hulman.oms.bean.User;
import com.hulman.oms.service.SentenceService;
import com.hulman.oms.service.SignService;
import com.hulman.oms.service.UserService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class SignController
{
    @Autowired
    private SignService signService;
    @Autowired
    private SentenceService sentenceService;
    @Autowired
    private HttpServletResponse response;
    private UserService userService;

    @GetMapping("/signs/{id}")
    public Result findSignById(@PathVariable Integer id)
    {
        Sign Sign = signService.findSignById(id);
        return new Result(Sign);
    }

    @GetMapping("/signs")
    public Result findSigns(Integer page, Integer limit, Integer userId, String userName, String locationIn, Integer workingTimeGreaterThan, Integer workingTimeLessThan, Integer state)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("userId", userId);
        map.put("userName", userName);
        map.put("locationIn", locationIn);
        if (workingTimeGreaterThan != null)
        {
            map.put("workingTimeGreaterThan", workingTimeGreaterThan * 3600);
        }
        if (workingTimeLessThan != null)
        {
            map.put("workingTimeLessThan", workingTimeLessThan * 3600);
        }
        map.put("state", state);
        return signService.findSignsResult(map);
    }

    @DeleteMapping("/signs/{ids}")
    public Result deleteSignById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            signService.deleteSignById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/signs")
    public Result saveSign(Sign Sign)
    {
        signService.saveSign(Sign);
        return Result.SUCCESS;
    }

    /**
     * 当前签到信息
     *
     * @return
     */
    @GetMapping("/signs/info")
    public Result findSignInfo()
    {
        Map<String, Object> data = new HashMap<>();
        User user = SubjectUtil.getUser();
        if (user != null)
        {
            data.put("user", user);
            Integer SignState = user.getSignState();
            //在岗状态，返回当前签到信息
            if (SignState == User.SIGN_STATE_ON)
            {
                Sign sign = signService.findLatestSignInSignByUserId(user.getId());
                if (sign != null)
                {
                    Integer workingTime = (int) ((System.currentTimeMillis() - sign.getTimeIn().getTime()) / 1000);
                    sign.setWorkingTime(workingTime);
                    data.put("sign", sign);
                }
            }
        }
        return new Result(data);
    }

    /**
     * 签到接口
     *
     * @param location
     * @param lng
     * @param lat
     * @return
     */
    @PostMapping("/signs/sign-in")
    public Result signIn(String location, Double lng, Double lat)
    {
        User user = SubjectUtil.getUser();
        signService.signIn(user.getId(), location, lng, lat);
        Sentence signSentence = sentenceService.randomCheckInSentence();
        String sentence = "";
        if (signSentence != null)
        {
            sentence = signSentence.getContent();
        }
        return new Result(sentence);
    }

    @PostMapping("/signs/sign-out")
    public Result signOut(String location, String note, Double lng, Double lat)
    {
        User user = SubjectUtil.getUser();
        signService.signOut(user.getId(), location, note, lng, lat);
        Sentence Sentence = sentenceService.randomCheckOutSentence();
        String sentence = "";
        if (Sentence != null)
        {
            sentence = Sentence.getContent();
        }
        return new Result(sentence);
    }

    /**
     * 强制签退
     *
     * @param userId
     * @return
     */
    @PostMapping("/signs/force-sign-out")
    public Result forceSignOut(Integer userId)
    {
        signService.signOut(userId, "", "", 0.0, 0.0);
        return new Result("已强制签退");
    }

    @GetMapping("/signs/export")
    public void exportSigns(String userName, String stationName, Integer state) throws IOException
    {
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=Signs.xlsx");

        Map<String, Object> map = new HashMap<>();

        map.put("userName", userName);
        map.put("stationName", stationName);
        map.put("state", state);

        List<Sign> Signs = signService.findSigns(map);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "考勤记录").head(Sign.class).build();
        excelWriter.write(Signs, sheet0);
        excelWriter.finish();
    }
}
